﻿using System;
using System.Web;
using System.Data.Common;
using System.Collections.Specialized;
using SyCODE.Component;
using SyCODE.Component.Cryptography;
using SyCODE.Component.DataFactory;
using SyCODE.Component.Security;
using SyCODE.Blog.Task;
using System.Web.Security;
using System.Xml;
namespace SyCODE.Blog
{
    /// <summary>
    /// 用户登录
    /// </summary>
    public class Login : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
			if (context.Request.HttpMethod != "POST")
			{
				Logout();
			}
			else
			{
				NameValueCollection nvc = new NameValueCollection(context.Request.Form);
                nvc.Set("pwd", SHA1.Encrypt(nvc["pwd"]));
                nvc.Add("ip", Function.GetUserIp());

				DBAM dbam = new DBAM();
				dbam.BuildParameters("login", nvc);

				DbDataReader dr = dbam.ExecuteReader();

				if (dr.Read())
				{
					string account = nvc["account"].ToLower();
					IssueTicket(account, dr.GetString(0), nvc["autologin"] == "1");
					nvc.Add("name", dr.GetString(0));

					//更新目标所访问博客的最新访问列表
					Processor.Assign(new VisitorTask(nvc));

					context.Response.ContentType = "text/xml";

                    XmlTextWriter writer = new XmlTextWriter(context.Response.OutputStream, context.Response.ContentEncoding);
					writer.WriteStartDocument();
					writer.WriteStartElement("message");
					writer.WriteAttributeString("account", account);
					writer.WriteAttributeString("name", dr.GetString(0));

					if (dr.NextResult() && dr.Read())
					{
						writer.WriteAttributeString("private", dr.GetValue(0).ToString());
						writer.WriteAttributeString("system", dr.GetValue(1).ToString());
					}
					writer.WriteEndElement();
					writer.WriteEndDocument();
					writer.Flush();
				}
				else
					Function.ClientScript("$id('syblog_login_form').elements['account'].focus();alert('" + StringResource.GetField("invalidlogin") + "')");

				dr.Close();
				dbam.Dispose();
			}
        }

		private void Logout()
		{
			HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
			cookie.Expires = DateTime.Now.AddYears(-999);
			cookie.Domain = FormsAuthentication.CookieDomain;
			HttpContext.Current.Response.Cookies.Add(cookie);
		}

        /// <summary>
        /// 颁发用户登录授权
        /// </summary>
        /// <param name="account">登录用户名</param>
        /// <param name="nickName">用户昵称</param>
        /// <param name="autologin">自动登录标示</param>
        public static void IssueTicket(string account, string nickName,bool autologin)
        {
            Ticket ticket = new Ticket(account, nickName);
            ticket.HttpOnly = false;
            ticket.Domain = FormsAuthentication.CookieDomain;
            if (autologin)
            {
                ticket.Expires = DateTime.Now.AddYears(50);
            }

            ticket.Issue(FormsAuthentication.FormsCookieName);
        }
    }
}
